<template>
  <div class="personData">
    <commonHeader :title="title" :subtitle="subtitle" @goBack="goBack" @goSubtitle="edit"></commonHeader>
    <div class="headdiv">
      <img :src="headimg" alt @click="upLoadBg()" />
      <label>点击更换头像</label>
      <!--    上传头像 -->
      <cropperImg ref="cropperImg" :aspectRatio="aspectRatio" @emitImgUrl="emitImgUrl"></cropperImg>
      <!--      <input type="file" ref="uploadBg" style="display: none" @change="uploadImg($event)" />-->
    </div>
    <div class="content">
      <div class="item">
        <div class="itemleft">
          <label>昵称</label>
        </div>
        <div class="itemright">
          <!-- <label>小蘑菇</label> -->
          <input type="text" v-model="username" placeholder="请输入昵称" />
        </div>
      </div>
      <div class="item">
        <div class="itemleft">
          <label>真实姓名</label>
          <label>(选填)</label>
        </div>
        <div class="itemright">
          <input type="text" v-model="realname" placeholder="请输入真实姓名" />
        </div>
      </div>
      <div class="item">
        <div class="itemleft">
          <label>简介</label>
        </div>
        <div class="itemright" @click="toDescribe()">
          <label>{{message}}</label>
          <van-icon name="arrow" color="#ffffff" />
        </div>
      </div>
      <div class="item">
        <div class="itemleft">
          <label>性别</label>
        </div>
        <div class="itemright" @click="show = true">
          <label>{{sex}}</label>
          <van-icon name="arrow" color="#ffffff" />
        </div>
        <van-action-sheet v-model="show" :actions="actions" @select="onSelect" />
      </div>
      <div class="item">
        <div class="itemleft">
          <label>生日</label>
        </div>
        <div class="itemright" @click="dateshow = true">
          <label>{{datetime}}</label>
          <van-icon name="arrow" color="#ffffff" />
        </div>
        <van-popup v-model="dateshow" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="选择年月"
            :min-date="minDate"
            :max-date="maxDate"
            :formatter="formatter"
            @confirm="confirmdate"
            @cancel="canceldate"
          />
        </van-popup>
      </div>
      <div class="item">
        <div class="itemleft">
          <label>地区</label>
        </div>
        <div class="itemright" @click="aresshow=true">
          <label>{{areatext}}</label>
          <van-icon name="arrow" color="#ffffff" />
        </div>
        <van-popup v-model="aresshow" position="bottom">
          <!-- <van-area title="地区选择" :area-list="areaList" columns-num="2"  @confirm="areasConfirm"  @cancel="areasCancel"/> -->
          <van-picker
            title="标题"
            show-toolbar
            :columns="columns"
            @confirm="areasConfirm"
            @cancel="areasCancel"
          />
        </van-popup>
      </div>
      <!-- <div class="itemh">
              <div class="item1">
                <div class="itemleft">
                  <label>收货地址</label>
                </div>
                <div class="itemright">
                    <van-icon name="arrow" color="#ffffff"/>
                </div>
              </div>
              <textarea class="address" v-model="address">

              </textarea>
      </div>-->
    </div>
  </div>
</template>

<script>
  import commonHeader from "../../components/common/commonHeader.vue";
  import cropperImg from "../../components/cropperImg.vue";
  import areaList from "../../assets/js/area.js";
  import { GETTOKEN, GETCITY, EDITUSER, GETUSERINFO } from "../../apis/mine";
  import * as qiniu from "qiniu-js";
  export default {
    name: "personalData",
    components: {
      commonHeader,
      cropperImg
    },
    data() {
      return {
        title: "个人资料",
        subtitle: "保存",
        headimg: "http://job.dayinyun.com/defaultImg.png", //头像默认
        show: false,
        actions: [{ name: "男" }, { name: "女" }],
        sex: "",
        username: "",
        realname: "",
        dateshow: false,
        minDate: new Date(1900, 0, 1),
        maxDate: new Date(),
        currentDate: new Date(1990, 0, 1),
        datetime: "",
        address: "",
        message: "写点什么吧~",
        areatext: "",
        aresshow: false,
        areaList: areaList,
        columnsdata: [],
        columns: [],
        code: "",
        aspectRatio: 1 //上传头像裁剪图片比例
      };
    },
    mounted() {
      // 监听页面滑动
      window.addEventListener("scroll", this.handleScroll, true);
      this.getcity();
      this.getuserinfo();
    },
    activated() {
      if (this.$route.params.message != undefined) {
        this.message = this.$route.params.message;
      }
    },
    methods: {
      // 返回
      goBack() {
        this.$router.back()
        // if (this.$systemInfo() === "android") {
        //   window.android.closeCurrentPage();
        // } else if (this.$systemInfo() === "ios") {
        //   window.webkit.messageHandlers.closeCurrentPage.postMessage(null);
        // }
      },
      // 上传图片
      upLoadBg() {
        this.$refs.cropperImg.clickUploadBeforeImg();
        // this.$refs.uploadBg.click();
      },
      uploadImg(e) {
        // console.log(e);
        let that = this;
        let file = e.target.files[0];
        var uploadInit;
        let getToken = GETTOKEN;
        getToken().then(res => {
          // console.log(res)
          if (res.data.code * 1 == 200) {
            uploadInit = res.data.data;
            if (uploadInit == "") {
              return;
            }
            this.uploadDomain = "http://up-z1.qiniup.com/";
            let key = new Date().getTime() + file.name;
            let config = {
              chunkSize: 8,
              region: qiniu.region.z1,
              domain: this.uploadDomain
            };
            var putExtra = {
              ...config
            };
            // console.log(qiniu);

            let observable = qiniu.upload(
              file,
              key,
              uploadInit,
              putExtra,
              config
            );
            let subscription = observable.subscribe({
              next(res) {
                let process = res.total.percent;
                that.process = Math.floor(process);
              },
              error(err) {
                Toast.fail("上传失败：" + err.message);
              },
              complete(res) {
                // that.code=res.key;
                that.headimg = "http://oss.dayinyun.com/" + res.key;
                // that.returnUrl();
              }
            });
          }
        });
      },
      cancelUpload() {
        // subscription.unsubscribe(); // 上传取消
      },
      returnUrl() {
        this.$emit(
          "getUploadParam",
          "http://oss.dayinyun.com/" + this.code,
          this.type
        );
      },
      onSelect(item) {
        // 默认情况下点击选项时不会自动收起
        // 可以通过 close-on-click-action 属性开启自动收起
        this.show = false;
        this.sex = item.name;
      },
      formatter(type, val) {
        if (type === "year") {
          return `${val}年`;
        } else if (type === "month") {
          return `${val}月`;
        } else {
          return `${val}日`;
        }
        return val;
      },
      confirmdate() {
        this.datetime = this.timeFormat(this.currentDate);
        this.dateshow = false;
      },
      canceldate() {
        this.dateshow = false;
      },
      timeFormat(time) {
        // 时间格式化 2019-09-08
        let year = time.getFullYear();
        let month = time.getMonth() + 1;
        if (month < 10) {
          month = "0" + month;
        }
        let day = time.getDate();
        if (day < 10) {
          day = "0" + day;
        }
        return year + "-" + month + "-" + day;
      },
      areasConfirm(addressElement, index) {
        console.log(index);
        this.areatext = addressElement;
        for (var i = 0; i < this.columnsdata.length; i++) {
          if (i == index) {
            this.code = this.columnsdata[i].code;
          }
        }
        this.aresshow = false;
      },
      areasCancel() {
        this.aresshow = false;
      },
      getcity() {
        let getcity = GETCITY;
        var that = this;
        getcity().then(res => {
          that.columnsdata = res.data.data;
          for (var i = 0; i < that.columnsdata.length; i++) {
            that.columns.push(that.columnsdata[i].name);
          }
        });
      },
      getuserinfo() {
        var that = this;
        let getuserinfo = GETUSERINFO;
        getuserinfo().then(res => {
          that.username = res.data.data.nickname;
          that.realname = res.data.data.true_name;
          that.message = res.data.data.describe;
          console.log(res.data.data.avatar);
          if (
            res.data.data.avatar != "" &&
            res.data.data.avatar != null &&
            res.data.data.avatar != "null" &&
            res.data.data.avatar != undefined
          ) {
            that.headimg = res.data.data.avatar;
          }

          that.datetime = res.data.data.birthday;
          that.sex = res.data.data.sex == 1 ? "男" : "女";
          var columnsdata = that.columnsdata;
          for (var i = 0; i < columnsdata.length; i++) {
            if (columnsdata[i].code == res.data.data.city) {
              that.code = columnsdata[i].code;
              that.areatext = columnsdata[i].name;
            }
          }
        });
      },
      edit() {
        var that = this;
        var data = {
          nickname: that.username,
          true_name: that.realname,
          describe: that.message,
          birthday: that.datetime,
          avatar: that.headimg,
          city: that.code,
          sex: that.sex == "男" ? 1 : 2
        };
        let edituser = EDITUSER;
        edituser(data).then(res => {
          if (res.data.code == 200) {
            // 更新用户信息
            if (this.$systemInfo() === "android") {
              window.android.updateUserInfo();
            } else if (this.$systemInfo() === "ios") {
              window.webkit.messageHandlers.updateUserInfo.postMessage(null);
            }
            // this.$router.push({ name: "mine" });
          } else {
            this.$toast.fail(res.data.message);
            // this.$router.push({ name: "mine" });
          }
        });
      },
      // 保存用户背景图片
      emitImgUrl(value) {
        this.headimg = value;
        // this.getuserinfo();//刷新页面
      },
      // 去简介页面
      toDescribe(){
        this.$router.push({name:'myProfile',params:{message:this.message}})
      }
    }
  };
</script>

<style lang="less" scoped>
  @import (reference) url(../../assets/less/common);
  .personData {
    .headdiv {
      margin-top: 1.94rem;
    }
    .headdiv img {
      display: block;
      width: 1.88rem;
      height: 1.88rem;
      border-radius: 0.94rem;
      margin: 0 auto;
    }
    .headdiv label {
      display: block;
      font-size: 0.34rem;
      color: #999999;
      font-weight: 500;
      text-align: center;
      margin-top: 0.12rem;
    }
    .content {
      margin-top: 0.2rem;
      padding-bottom: 0.3rem;
      .item {
        width: 93%;
        margin: 0 auto;
        display: flex;
        justify-content: space-between;
        padding-bottom: 0.33rem;
        padding-top: 0.33rem;
        border-bottom: 1px solid rgba(102, 102, 102, 0.4);
        color: rgba(255, 255, 255, 1);
        font-weight: 500;
        font-size: 0.34rem;
        .itemleft {
          label:nth-child(2) {
            color: #666666 !important;
          }
        }
        .itemright {
          display: flex;
          align-items: center;
        }
        .itemright input {
          display: block;
          width: 4rem;
          border: none;
          background: none;
          text-align: right;
        }
        .itemright label {
          display: block;
          width: 4rem;
          border: none;
          background: none;
          text-align: right;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
      .itemh {
        width: 93%;
        margin: 0 auto;
        padding-bottom: 0.33rem;
        padding-top: 0.33rem;
        border-bottom: 1px solid rgba(102, 102, 102, 0.4);
        color: rgba(255, 255, 255, 1);
        font-weight: 500;
        font-size: 0.34rem;
        .item1 {
          display: flex;
          justify-content: space-between;
        }
        .address {
          width: 100%;
          margin-top: 0.13rem;
          background: none;
          display: block;
          text-align: left;
        }
      }
      /deep/.van-icon {
        font-size: 0.3rem;
        margin-left: 0.1rem;
      }
    }
  }
</style>
